﻿using Microsoft.AspNet.Identity;
using MVCForum.Web.Identity.EF.Entities;
using System;
using System.Data.Entity;
using System.Linq;
using System.Threading.Tasks;

namespace MVCForum.Web.Identity.EF {

	public class RoleStore : IRoleStore<Role>, IDisposable {
		private Boolean disposed = false;
		private DbContext context;
		private EntityStore<Role> roleStore;

		public RoleStore(DbContext context) {
			if (context == null) {
				throw new ArgumentNullException("context");
			}
			this.context = context;
			this.roleStore = new EntityStore<Role>(context);
		}

		public void Dispose() {
			this.Dispose(true);
			GC.SuppressFinalize(this);
		}

		private void Dispose(Boolean disposing) {
			if (disposing && !this.disposed) {
				this.context.Dispose();
			}
			this.disposed = true;
			this.context = null;
			this.roleStore = null;
		}

		public Task CreateAsync(Role role) {
			if (role == null) {
				throw new ArgumentNullException("role");
			}

			this.roleStore.Create(role);
			this.context.SaveChanges();
			return Task.FromResult<Object>(null);
		}

		public Task DeleteAsync(Role role) {
			throw new NotImplementedException();
		}

		public Task<Role> FindByIdAsync(String roleId) {
			return this.roleStore.GetByIdAsync(roleId);
		}

		public Task<Role> FindByNameAsync(String roleName) {
			IQueryable<Role> entitySet = this.roleStore.EntitySet.Where(r => r.Name.ToUpper() == roleName.ToUpper());
			return Task.FromResult<Role>(entitySet.FirstOrDefault<Role>());
		}

		public Task UpdateAsync(Role role) {
			if (role == null) {
				throw new ArgumentNullException("role");
			}
			this.context.SaveChanges();
			return Task.FromResult<Object>(null);
		}
	}
}